package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.mapper.MySqlMapper;
import com.innovation.ic.b1b.monitor.base.model.Mysql;
import com.innovation.ic.b1b.monitor.base.model.MysqlAvailableJob;
import com.innovation.ic.b1b.monitor.base.pojo.MySqlPojo;
import com.innovation.ic.b1b.monitor.base.pojo.SqlServerPojo;
import com.innovation.ic.b1b.monitor.base.pojo.constant.TableNameConstant;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.pojo.variable.mysql.MysqlInfoRespPojo;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.EnvironmentService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MySqlService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MysqlAvailableJobLogHistoryService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MysqlAvailableJobLogService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.MysqlAvailableJobService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceHelper;
import com.innovation.ic.b1b.monitor.base.vo.MySqlVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class MySqlServiceImpl extends ServiceImpl<MySqlMapper, Mysql> implements MySqlService {

    @Resource
    private EnvironmentService environmentService;

    @Resource
    private MysqlAvailableJobService mysqlAvailableJobService;


    @Resource
    private MysqlAvailableJobLogService mysqlAvailableJobLogService;


    @Resource
    private MysqlAvailableJobLogHistoryService mysqlAvailableJobLogHistoryService;


    @Resource
    private ServiceHelper serviceHelper;


    @Override
    public ServiceResult addMySql(MySqlVo mySqlVo) {
        ServiceResult serviceResult = new ServiceResult();
        QueryWrapper<Mysql> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", mySqlVo.getName());
        queryWrapper.eq("system_id", mySqlVo.getSystemId());
        queryWrapper.eq("environment_id", mySqlVo.getEnvironmentId());
        queryWrapper.eq("url", mySqlVo.getUrl());
        Integer id = mySqlVo.getId();
        Mysql mysql = new Mysql();
        BeanUtil.copyProperties(mySqlVo, mysql);
        if (id == null) {
            List<Mysql> mysqlList = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(mysqlList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("重复,请重新添加");
                return serviceResult;
            }
            QueryWrapper<Mysql> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", mySqlVo.getName());
            List<Mysql> mysqlName = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(mysqlName)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }
            this.baseMapper.insert(mysql);
        } else {
            queryWrapper.ne("id", id);
            List<Mysql> mysqlList = this.baseMapper.selectList(queryWrapper);
            if (!CollectionUtils.isEmpty(mysqlList)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("重复,请重新添加");
                return serviceResult;
            }
            QueryWrapper<Mysql> queryWrapperName = new QueryWrapper<>();
            queryWrapperName.eq("name", mySqlVo.getName());
            queryWrapperName.ne("id", id);
            List<Mysql> mysqlName = this.baseMapper.selectList(queryWrapperName);
            if (!CollectionUtils.isEmpty(mysqlName)) {
                serviceResult.setSuccess(Boolean.FALSE);
                serviceResult.setMessage("名字不能重复");
                return serviceResult;
            }

            this.baseMapper.updateById(mysql);
        }
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("成功");
        return serviceResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMySql(MySqlVo mySqlVo) {
        Integer id = mySqlVo.getId();
        this.baseMapper.deleteById(id);
        this.deleteByMySqlId(id);
    }

    @Override
    public MySqlPojo findById(MySqlVo mySqlVo,Boolean mainDb) {
        return this.baseMapper.findById(mySqlVo.getId());
    }

    @Override
    public ServiceResult<PageInfo<SqlServerPojo>> findByPage(MySqlVo mySqlVo,Boolean mainDb) {
        ServiceResult<PageInfo<SqlServerPojo>> serviceResult = new ServiceResult<>();
        //当环境id不为空时
        Integer environmentId = mySqlVo.getEnvironmentId();
        if (environmentId != null) {
            List<Integer> environmentIds = environmentService.findByName(environmentId);
            if (!CollectionUtils.isEmpty(environmentIds)) {
                mySqlVo.setEnvironmentIds(environmentIds);
            }
        }
        PageHelper.startPage(mySqlVo.getPageNo(), mySqlVo.getPageSize());
        List<SqlServerPojo> environmentPojoList = this.baseMapper.findByPage(mySqlVo);
        PageInfo<SqlServerPojo> pageInfo = new PageInfo<>(environmentPojoList);
        serviceResult.setResult(pageInfo);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    @Override
    public void deleteBySystemId(Integer systemId) {
        if (systemId == null) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("system_id", systemId);
        this.baseMapper.deleteByMap(map);
    }

    /**
     * 同时删除mysql定时任务和日志和历史日志
     *
     * @param environmentId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByEnvironmentId(Integer environmentId) {
        if (environmentId == null) {
            return;
        }
        QueryWrapper<Mysql> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("environment_id", environmentId);
        List<Mysql> mysqlList = this.baseMapper.selectList(queryWrapper);
        for (Mysql mysql : mysqlList) {
            this.deleteByMySqlId(mysql.getId());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("environment_id", environmentId);
        this.baseMapper.deleteByMap(map);
    }

    /**
     * 查询mysql信息列表
     *
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<MysqlInfoRespPojo>> queryMysqlList(Boolean mainDb) {
        List<MysqlInfoRespPojo> result = this.baseMapper.queryMysqlList();
        ServiceResult<List<MysqlInfoRespPojo>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }


    /**
     * 删除关联mysql所有信息
     *
     * @param mySqlId
     */
    private void deleteByMySqlId(Integer mySqlId) {
        //删除定时任务
        List<MysqlAvailableJob> mysqlAvailableJobList = mysqlAvailableJobService.findByMysqlId(mySqlId);
        for (MysqlAvailableJob mysqlAvailableJob : mysqlAvailableJobList) {
            Integer id = mysqlAvailableJob.getId();
            String jobId = TableNameConstant.MYSQL_AVAILABLE_JOB + "_" + id;
            serviceHelper.getQuartzManager().deleteScheduleJob(jobId);
            mysqlAvailableJobService.delete(id);
            //删除日志和历史日志
            mysqlAvailableJobLogService.deleteByAvailableJobId(id);
            mysqlAvailableJobLogHistoryService.deleteByAvailableJobId(id);
        }

    }
}